package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import com.cskaoyan.shopping.utils.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ycc
 * @date 2022/07/29 16:30:51
 */
@Service
@Slf4j
public class ICartServiceImpl implements ICartService {
    @Autowired
    ItemMapper itemMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            //参数验证
            request.requestCheck();
            //取出redis中的数据
            String userId = request.getUserId().toString();
            Map<Long, CartProductDto> map = redissonClient.getMap(userId);
            List<CartProductDto> productDots = new ArrayList<>(map.values());
            //执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            response.setCartProductDtos(productDots);
        } catch (Exception e) {
            log.error("ICartServiceImpl.getCartListById occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            //先执行参数验证
            request.requestCheck();
            //获取参数
            Long userId = request.getUserId();
            Long itemId = request.getItemId();
            Integer num = request.getNum();
            String userIdStr = "" + userId;

            Map<Long, CartProductDto> cartMap = redissonClient.getMap(userIdStr);
            //判断购物车中是否有该信息
            CartProductDto productExists = cartMap.get(itemId);
            if (productExists == null) {
                //没有——>将数据存储进redis
                Item item = itemMapper.selectByPrimaryKey(itemId);
                item.setNum(num);
                CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
                cartProductDto.setChecked(GlobalConstants.CART_ITEM_UNCHECKED);
                cartMap.put(itemId,cartProductDto);
            }else {
                //有——>更改商品数量
                productExists.setProductNum(productExists.getProductNum()+num);
                cartMap.put(itemId,productExists);
            }
            //执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.addToCart occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            String checked = request.getChecked();
            Long itemId = request.getItemId();
            Integer num = request.getNum();
            Long userId = request.getUserId();
            Map<Long, CartProductDto> map = redissonClient.getMap(UserInfoUtil.UserIdStr(userId));
            CartProductDto productDto = map.get(itemId);
            productDto.setProductNum(num.longValue());
            productDto.setChecked(checked);
            map.put(itemId,productDto);
            //执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.updateCartNum occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            String checked = request.getChecked();
            Map<Long, CartProductDto> map = redissonClient.getMap(UserInfoUtil.UserIdStr(userId));
            for (Long productId : map.keySet()) {
                CartProductDto productDto = map.get(productId);
                productDto.setChecked(checked);
                map.put(productId,productDto);
            }
            //成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.checkAllCartItem occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Long itemId = request.getItemId();
            Map<Long, CartProductDto> map = redissonClient.getMap(UserInfoUtil.UserIdStr(userId));
            map.remove(itemId);
            //成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.deleteCartItem occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Map<Long, CartProductDto> map = redissonClient.getMap(UserInfoUtil.UserIdStr(userId));
            //判断购物车中的商品是否被选中
            for (Long productId : map.keySet()) {
                CartProductDto productDto = map.get(productId);
                //被选中——>删除
                if (productDto.getChecked().equals(GlobalConstants.CART_ITEM_CHECKED)) {
                    map.remove(productId);
                }
            }
            //成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.deleteCheckedItem occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            List<Long> productIds = request.getProductIds();
            Map<Long, CartProductDto> map = redissonClient.getMap(UserInfoUtil.UserIdStr(userId));
            for (Long productId : productIds) {
                map.remove(productId);
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("ICartServiceImpl.clearCartItemByUserID occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
}
